import { Context } from 'koa';
import { controller, post, get } from '../utils/decorator/apiDecorator';
import { returnResult } from '../utils/response/returnResult';
import { jwtConf } from '../config/index';
import jwt from 'jsonwebtoken';
import userService from '../services/user';

//生成用户token
function getToken(_id: string): string {
    return jwt.sign({ _id: _id }, jwtConf.SECRET, { expiresIn: jwtConf.EXPIRES_IN });
}
@controller('/user')
export default class UserController {
    /**
     * 登录
     * @param ctx 
     */
    @post('/login')
    async login(ctx: Context) {
        const user = await userService.login(ctx.request.body.email, ctx.request.body.password);
        ctx.body = returnResult.success({ token: getToken(user._id) });
    }
    /**
     * 创建用户
     * @param ctx 
     */
    @post('/createUser')
    async createUser(ctx: Context) {        
        const user = await userService.create(ctx.request.body);
        ctx.body = returnResult.success({ token: getToken(user._id) });
    }
    @get('/findUser')
    async findUser(ctx: Context) {
        const user = await userService.findById(ctx.user._id);
        ctx.body = returnResult.success(user);
    }
}